Imports System.Windows.Forms

Public Class frmCalcAggregate

    Dim SQLFormat As String = "INSERT INTO {0} (RecID,Station_ID,Date_Time,PCode,LEW_Pct,Depth_M,CCode,Agency,RCode,Result,Validated,Track_ID) VALUES ({1})"

    Private Enum enumAggregate
        Hour
        Day
        Week
        Month
        CalendarYear
        WaterYear
        ClimaticYear
        Growing
        Season
        SeasonAnnual
        Rolling
    End Enum

    Private Enum enumOperation
        Mean
        GeoMean
        Median
        Sum
    End Enum

    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
        Try
            MainForm.WriteProgress("Compiling data")

            Dim CCode As String = Project.DB.GetPickList(cboCCodeOut)
            Dim SCode As String = Project.DB.GetPickList(cboSCodeOut)
            Dim LCode As String = Project.DB.GetPickList(cboLCodeOut)
            If CCode.StartsWith("(Create") Then
                WarningMsg("You must select a valid CCode before continuing.")
                Exit Sub
            End If

            Dim lstDataRecords As New Generic.List(Of clsDataRecord)

            Dim DataTable As clsDataTable

            If cboSummaryField.SelectedIndex = 0 Then 'this is original code
                DataTable = New clsDataTable(Project, clsProject.TempData)
                lstDataRecords = DataTable.SelectRecords(, "Date_Time")
                DataTable.Close()
            Else 'revised to do spatial aggregation
                Dim dr As DbDataReader = Project.DB.ExecuteReader("SELECT Stations.{0} Station_ID, Dta.Date_Time, Dta.PCode, Dta.CCode, Dta.LCode, Dta.SCode, Dta.QCode, Dta.Result, Dta.RCode, Dta.LEW_Pct, Dta.Depth_M, Dta.Agency, Dta.Validated, Dta.Track_ID FROM {1} Dta, Stations WHERE Dta.Station_ID=Stations.Station_ID ORDER BY Dta.Date_Time", cboSummaryField.Text, clsProject.TempData)
                While dr IsNot Nothing And dr.Read
                    Dim ar(13) As Object
                    dr.GetValues(ar)
                    lstDataRecords.Add(New clsDataRecord(ar))
                End While
            End If

            If lstDataRecords Is Nothing OrElse lstDataRecords.Count = 0 Then WarningMsg("There are no selected records.") : Exit Sub

            Dim dictExistData As New Generic.SortedDictionary(Of String, Generic.List(Of clsDataRecord))

            For Each dataRecord As clsDataRecord In lstDataRecords
                With dataRecord
                    Dim key As String = .StationID & .PCode
                    If Not dictExistData.ContainsKey(key) Then dictExistData.Add(key, New Generic.List(Of clsDataRecord))
                    dictExistData(key).Add(dataRecord)
                End With
            Next

            Dim AggStep As enumAggregate = Me.cboAggregation.SelectedIndex
            Dim Operation As enumOperation = Me.cboOperation.SelectedIndex
            Dim OperationSeason As enumOperation = Me.cboOperationSeason.SelectedIndex
            If AggStep = enumAggregate.Rolling And Operation = enumOperation.Sum Then
                WarningMsg("You cannot select the Rolling Average Aggregation Period and Total Operation at the same time.")
                Exit Sub
            End If

            Dim lstNewData As New Generic.List(Of clsDataRecord)
            Dim lstStations As New Generic.List(Of String)
            Dim duplicateDates As Boolean = False
            Dim multipleWidth_Depths As Boolean = False
            Dim numRolling As Integer = 0
            If AggStep = enumAggregate.Rolling Then
                Dim s As String = InputBox("Enter the number of consecutive observations what will be used to compute the rolling averages:", "Aggregate Data", 7)
                If s = "" Then Exit Sub
                numRolling = Val(s)
                If numRolling <= 0 Or numRolling <> Val(s) Then WarningMsg("You must enter a positive integer for the number of observations!") : Exit Sub
            End If

            'loop for each station ID/pcode pair
            For Each kv As Generic.KeyValuePair(Of String, Generic.List(Of clsDataRecord)) In dictExistData
                Dim Depth As Single, Width As Single
                With kv.Value.Item(0)
                    Depth = .DepthM
                    Width = .LEWPct
                    If cboSummaryField.SelectedIndex > 0 AndAlso chkAppendStations.Checked AndAlso Not lstStations.Contains(.StationID) Then lstStations.Add(.StationID)
                End With
                If AggStep = enumAggregate.Rolling Then
                    If kv.Value.Count >= numRolling Then
                        For i As Integer = Int((numRolling + 1) / 2) - 1 To kv.Value.Count - Int(numRolling / 2) - 1
                            Dim sumy As Double = 0
                            Dim ycount As Integer = 0
                            For j As Integer = i - numRolling \ 2 To i + numRolling \ 2
                                If j >= 0 And j < kv.Value.Count Then
                                    sumy += kv.Value.Item(j).Result
                                    ycount += 1
                                End If
                            Next j
                            With kv.Value.Item(i)
                                Dim NewRec As New clsDataRecord(.StationID, .DateTime, .PCode, sumy / ycount, CCode, "", .LEWPct, .DepthM, .Agency, False, Nothing, LCode, SCode)
                                If .DepthM <> Depth Or .LEWPct <> Width Then multipleWidth_Depths = True
                                lstNewData.Add(NewRec)
                            End With
                        Next i
                    End If
                Else
                    Dim ThisDate As Date = kv.Value.Item(0).DateTime
                    'set at beginning of period
                    Dim MinDate As Date = ThisDate
                    Dim MinDateWinter As Date
                    With MinDate
                        Select Case AggStep
                            Case enumAggregate.Hour : MinDate = New Date(.Year, .Month, .Day, .Hour, 0, 0)
                            Case enumAggregate.Day : MinDate = New Date(.Year, .Month, .Day)
                            Case enumAggregate.Week
                                MinDate = New Date(.Year, .Month, .Day)
                                MinDate = MinDate.AddDays(-MinDate.DayOfWeek) 'change to first day of week (sunday)
                            Case enumAggregate.Month : MinDate = New Date(.Year, .Month, 1)
                            Case enumAggregate.CalendarYear, enumAggregate.SeasonAnnual : MinDate = New Date(.Year, 1, 1)
                            Case enumAggregate.WaterYear : MinDate = New Date(IIf(.Month < 10, .Year - 1, .Year), 10, 1)
                            Case enumAggregate.ClimaticYear : MinDate = New Date(IIf(.Month < 4, .Year - 1, .Year), 4, 1)
                            Case enumAggregate.Growing : MinDate = New Date(IIf(.DayOfYear < New Date(.Year, cboMonth2.SelectedIndex + 1, cboDay2.SelectedIndex + 1).DayOfYear, .Year, .Year + 1), cboMonth1.SelectedIndex + 1, cboDay1.SelectedIndex + 1)
                            Case enumAggregate.Season
                                MinDateWinter = New Date(.Year, cboMonth1.SelectedIndex + 1, cboDay1.SelectedIndex + 1)
                                For SeasonNum As Integer = 0 To 3
                                    Dim MinSeasonDay As Date = New Date(MinDate.Year, 1, 1).AddDays(MinDateWinter.DayOfYear - 1).AddMonths(SeasonNum * 3)
                                    Dim MaxSeasonDay As Date = MinSeasonDay.AddMonths(3)
                                    If MinDate >= MinSeasonDay And MinDate < MaxSeasonDay Then Exit For
                                Next
                        End Select
                    End With

                    Dim i As Integer = 0
                    Dim NextDate As Date = MinDate 'will immediately increment below

                    If AggStep = enumAggregate.Growing And kv.Value.Item(0).DateTime < NextDate Then 'get first date in growing season
                        Do
                            i += 1
                            If i > kv.Value.Count - 1 Then
                                Continue For
                            Else
                                ThisDate = kv.Value.Item(i).DateTime
                            End If
                        Loop Until ThisDate >= NextDate
                        NextDate = MinDate
                    End If

                    Do
                        Select Case AggStep
                            Case enumAggregate.Hour : NextDate = NextDate.AddHours(1)
                            Case enumAggregate.Day : NextDate = NextDate.AddDays(1)
                            Case enumAggregate.Week : NextDate = NextDate.AddDays(7)
                            Case enumAggregate.Month : NextDate = NextDate.AddMonths(1)
                            Case enumAggregate.CalendarYear To enumAggregate.ClimaticYear, enumAggregate.SeasonAnnual : NextDate = NextDate.AddYears(1)
                            Case enumAggregate.Growing : NextDate = New Date(NextDate.Year, cboMonth2.SelectedIndex + 1, cboDay1.SelectedIndex + 1)
                            Case enumAggregate.Season : NextDate = NextDate.AddMonths(3)
                        End Select
                        'may need to hold in 4 item array if seasonal->annual; if have data for all four seasons, will save annual value
                        'for all other types, store in item 0
                        Dim lstResult(3) As Generic.List(Of Single)
                        For s As Integer = 0 To 3
                            lstResult(s) = New Generic.List(Of Single)
                        Next

                        Dim FirstRec As clsDataRecord = kv.Value.Item(i)
                        Do
                            With kv.Value.Item(i)
                                Dim SeasonNum As Integer = 0
                                ThisDate = .DateTime
                                If ThisDate >= NextDate Then Exit Do
                                If AggStep = enumAggregate.SeasonAnnual Then 'determine which season current date is in
                                    For SeasonNum = 0 To 3
                                        Dim MinSeasonDay As Date = New Date(ThisDate.Year, 1, 1).AddDays(MinDateWinter.DayOfYear - 1).AddMonths(SeasonNum * 3)
                                        Dim MaxSeasonDay As Date = MinSeasonDay.AddMonths(3)
                                        If ThisDate >= MinSeasonDay And ThisDate < MaxSeasonDay Then Exit For
                                    Next
                                End If
                                lstResult(SeasonNum).Add(.Result)
                                If i > 0 AndAlso ThisDate.Subtract(CDate(kv.Value.Item(i - 1).DateTime)).TotalSeconds = 0 Then duplicateDates = True
                                i += 1
                                If i > kv.Value.Count - 1 Then
                                    Exit Do
                                Else
                                    If .DepthM <> Depth Or .LEWPct <> Width Then multipleWidth_Depths = True
                                End If
                            End With
                        Loop

                        With FirstRec 'most of new record is taken from first record in period
                            'for summing operations, set new data date/time to end of period; otherwise to beginning or middle of period
                            Dim AggDate As Date
                            Select Case AggStep
                                Case enumAggregate.Hour : AggDate = NextDate.AddMinutes(IIf(Operation = enumOperation.Sum, 0, -30))
                                Case enumAggregate.Day : AggDate = NextDate.AddHours(IIf(Operation = enumOperation.Sum, 0, -12))
                                Case enumAggregate.Week : AggDate = NextDate.AddDays(IIf(Operation = enumOperation.Sum, 0, -3.5))
                                Case enumAggregate.Month : AggDate = NextDate.AddMonths(IIf(Operation = enumOperation.Sum, 0, -1))
                                Case enumAggregate.CalendarYear To enumAggregate.ClimaticYear, enumAggregate.SeasonAnnual : AggDate = NextDate.AddYears(IIf(Operation = enumOperation.Sum, 0, -1))
                                Case enumAggregate.Growing : AggDate = IIf(Operation = enumOperation.Sum, NextDate, New Date(NextDate.Year, cboMonth1.SelectedIndex + 1, cboDay1.SelectedIndex + 1))
                                Case enumAggregate.Season : AggDate = NextDate.AddMonths(IIf(Operation = enumOperation.Sum, 0, -3))
                            End Select
                            Select Case AggStep
                                Case enumAggregate.SeasonAnnual
                                    'add new record only if data present in all four seasons
                                    Dim lstSeasonResult As New Generic.List(Of Single)
                                    Dim SeasonMissing As Boolean = False
                                    For s As Integer = 0 To 3
                                        If lstResult(s).Count = 0 Then
                                            SeasonMissing = True
                                            Exit For
                                        Else
                                            lstSeasonResult.Add(Compute(lstResult(s), Operation))
                                        End If
                                    Next
                                    If Not SeasonMissing Then
                                        Dim NewValue As Double = Compute(lstSeasonResult, OperationSeason)
                                        Dim NewRec As New clsDataRecord(.StationID, AggDate, .PCode, NewValue, CCode, "", .LEWPct, .DepthM, .Agency, False, Nothing, LCode, SCode)
                                        lstNewData.Add(NewRec)
                                    End If
                                Case Else
                                    Dim NewValue As Double = Compute(lstResult(0), Operation)
                                    Dim NewRec As New clsDataRecord(.StationID, AggDate, .PCode, NewValue, CCode, "", .LEWPct, .DepthM, .Agency, False, Nothing, LCode, SCode)
                                    lstNewData.Add(NewRec)
                            End Select
                        End With

                        If AggStep = enumAggregate.Growing Then
                            Dim NextSpring As Date = New Date(NextDate.Year + 1, cboMonth1.SelectedIndex + 1, cboDay1.SelectedIndex + 1)
                            Do
                                i += 1
                                If i > kv.Value.Count - 1 Then
                                    Exit Do
                                Else
                                    ThisDate = kv.Value.Item(i).DateTime
                                End If
                            Loop Until ThisDate >= NextSpring
                            NextDate = NextSpring
                        End If
                    Loop Until i > kv.Value.Count - 1
                End If
            Next

            MainForm.ProgressComplete()

            'only warn about duplicates if doing no spatial aggregation (which are likely to have duplicates)
            If cboSummaryField.SelectedIndex = 0 And duplicateDates AndAlso WarningMsg("One or more duplicate dates were found for a given station and PCode. This may be due to data having multiple CCodes included in the selected dataset (such as from a previous data aggregation operation). Do you want to continue?") = Windows.Forms.DialogResult.Cancel Then Exit Sub
            If multipleWidth_Depths AndAlso WarningMsg("One or more calculated records were based on source records having non-constant depths or widths. Do you want to continue?") = Windows.Forms.DialogResult.Cancel Then Exit Sub

            Dim TableName As String = cboTableName.Text
            If cboTableName.SelectedIndex = 0 Then TableName = ActiveBrowser.FullTableName

            If MessageBox.Show(StringFormat("You are about to append {0} computed values to the selected Working table ({1}). The calculated values will use the specified CCode ({2}), SCode ({3}), and LCode ({4}).\n\nBecause the table will be permanently modified, it may be difficult to undo this operation. Are you sure you want to continue?", lstNewData.Count, TableName, cboCCodeOut.Text.Trim, cboSCodeOut.Text.Trim, cboLCodeOut.Text.Trim), "Aggregate Data", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK Then
                DataTable = New clsDataTable(Project, TableName)

                Dim NumFound As Integer = DataTable.GetCount("CCode='{0}'", CCode)
                If NumFound > 0 Then
                    Select Case MessageBox.Show(StringFormat("Before computing all values, do you want to delete all {0} existing records in this Working table that have the specified CCode ({1}), SCode ({2}), and LCode ({3})?", NumFound, CCode.Trim, SCode.Trim, LCode.Trim), "Aggregate Data", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
                        Case Windows.Forms.DialogResult.Yes
                            MainForm.WriteProgress("Deleting old records...")
                            DataTable.DeleteRecords("CCode{0} AND SCode{1} AND LCode{2}",
                                                    IIf(CCode = "", " IS NULL", "='" & CCode & "'"),
                                                    IIf(SCode = "", " IS NULL", "='" & SCode & "'"),
                                                    IIf(LCode = "", " IS NULL", "='" & LCode & "'"))
                        Case Windows.Forms.DialogResult.No
                        Case Windows.Forms.DialogResult.Cancel
                            Exit Sub
                    End Select
                End If

                Try
                    For Each datarecord As clsDataRecord In lstNewData
                        If Not DataTable.InsertRecord(datarecord) Then WarningMsg("Unable to update table.") : Exit Sub
                        MainForm.WriteProgress(lstNewData.IndexOf(datarecord), lstNewData.Count - 1, "Saving computed values...", ProgressBarStyle.Continuous)
                    Next
                    DataTable.Close(clsDataTable.enumEndTransaction.Commit)
                    IniFile.SetKey(clsWRDBIniFile.enumSection.Application, clsWRDBIniFile.enumKey.AppLastEditTime, Now.ToString(System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat))
                Catch ex As Exception
                    DataTable.Close(clsDataTable.enumEndTransaction.Rollback)
                Finally
                    DataTable.Close()
                End Try
                Project.UpdateTrackingRecord(TableName, , True)
                RefreshAllForms()
                Close()
                MainForm.OpenDataTable(TableName)
            End If

            If cboSummaryField.SelectedIndex > 0 AndAlso chkAppendStations.Checked AndAlso lstStations.Count > 0 AndAlso
                WarningMsgFmt("Do you want to update the Stations table with the {0} new values associated with the spatial aggregation field ({1})?", lstStations.Count, cboSummaryField.Text) Then
                Dim sw As IO.StreamWriter = Nothing
                Try
                    Dim TempFile As String = clsProject.TempPath & "\Stations.txt"
                    sw = New IO.StreamWriter(TempFile)
                    sw.WriteLine(("Station_ID\tStation_Name\tStation_Type\tLatitude\tLongitude\tRMile\tOther\t" & cboSummaryField.Text).Replace("\t", vbTab))
                    For Each StaID As String In lstStations
                        Dim SumLat As Double = 0
                        Dim SumLon As Double = 0
                        Dim Count As Integer = 0
                        Dim dr As DbDataReader = Nothing
                        Dim StaName As String = ""
                        Dim StaType As String = "Spatial Aggregate on " & cboSummaryField.Text
                        Dim RMile As String = ""
                        Dim Other As String = ""
                        Select Case cboSummaryField.Text
                            Case "Branch_ID"
                                dr = Project.DB.ExecuteReader("SELECT Branch_Name,DS_Branch_ID,DS_Branch_RM FROM Branches WHERE Branch_ID='{0}'", StaID)
                                If dr IsNot Nothing AndAlso dr.HasRows Then
                                    StaName = TestNull(dr.GetValue(0), "")
                                    RMile = TestNull(dr.GetValue(2), "")
                                    Other = "DS_Branch_ID = " & TestNull(dr.GetValue(1), "")
                                End If
                            Case "Station_Type", "WaterBodyType", "Basin_Name", "EcoRegion", "PlanRegion"
                                dr = Project.DB.ExecuteReader("SELECT Description FROM Validation WHERE Field_Name='{0}' AND Valid_Value='{1}'", cboSummaryField.Text.ToUpper, StaID)
                                If dr IsNot Nothing AndAlso dr.HasRows Then
                                    StaName = TestNull(dr.GetValue(0), "")
                                End If
                            Case "County_Name", "HUC", "Reach_ID", "Remarks", "Other"
                        End Select
                        dr.Close()
                        dr = Project.DB.ExecuteReader("SELECT SUM(Latitude) as Lat, SUM(Longitude) as Lon, COUNT(*) as Cnt FROM Stations WHERE {0}='{1}' AND Latitude IS NOT NULL AND Longitude IS NOT NULL GROUP BY {0}", cboSummaryField.Text, StaID)
                        If dr IsNot Nothing And dr.HasRows Then
                            SumLat = dr.GetValue(0)
                            SumLon = dr.GetValue(1)
                            Count = dr.GetValue(2)
                        End If
                        dr.Close()
                        sw.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{0}".Replace("\t", vbTab), StaID.ToUpper, StaName, StaType, IIf(Count = 0, "", Math.Round(SumLat / Count, 4)), IIf(Count = 0, "", Math.Round(SumLon / Count, 4)), RMile, Other)
                    Next
                    sw.Close()
                    Project.ImportTable("Stations", TempFile, True, True)
                Catch ex As Exception
                    Throw New Exception("Error occurred while writing temporary file to be imported to Stations.", ex)
                Finally
                    If sw IsNot Nothing Then
                        sw.Close()
                        sw.Dispose()
                    End If
                End Try
            End If

        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            MainForm.ProgressComplete()
        End Try
    End Sub

    Private Function Compute(ByVal lst As Generic.List(Of Single), ByVal Operation As enumOperation) As Single
        Dim Sum As Single = 0
        Dim Num As Integer = 0
        For Each v As Single In lst
            If Operation = enumOperation.GeoMean Then
                If v > 0 Then
                    Sum += Math.Log(v)
                    Num += 1
                End If
            Else
                Sum += v
                Num += 1
            End If
        Next
        Select Case Operation
            Case enumOperation.Mean
                If Num = 0 Then Return 0 Else Return Sum / Num
            Case enumOperation.Sum
                Return Sum
            Case enumOperation.GeoMean
                If Num = 0 Then Return 0 Else Return Math.Exp(Sum / Num)
            Case enumOperation.Median
                lst.Sort()
                If lst.Count Mod 2 = 0 Then 'is even, average middle two values
                    Dim idx As Integer = lst.Count / 2 - 1
                    Return (lst(idx) + lst(idx + 1)) / 2.0
                Else
                    Dim idx As Integer = (lst.Count - 1) / 2
                    Return lst(idx)
                End If
        End Select
    End Function

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Sub frmCalc_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveControlValues(REGAPP, Me)
        If cboAggregation.Text.StartsWith("Four") Then
            SaveSetting(REGAPP, Name, "WinterMonth", cboMonth1.Text)
            SaveSetting(REGAPP, Name, "WinterDay", cboDay1.Text)
        ElseIf cboAggregation.Text.StartsWith("Growing") Then
            SaveSetting(REGAPP, Name, "GrowingMonth1", cboMonth1.Text)
            SaveSetting(REGAPP, Name, "GrowingDay1", cboDay1.Text)
            SaveSetting(REGAPP, Name, "GrowingMonth2", cboMonth2.Text)
            SaveSetting(REGAPP, Name, "GrowingDay2", cboDay2.Text)
        End If
    End Sub

    Private Sub frmCalc_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Project.DB.FillPickList(cboCCodeOut, "", "CCodes", "CCode", "CCode_Name", "(Create New)")
            Project.FillPickListValidation(cboSCodeOut, "SCODE")
            Project.FillPickListValidation(cboLCodeOut, "LCODE")
            frmCalc.RefreshTableList(cboTableName)
            GetControlValues(REGAPP, Me)
        Catch ex As Exception
            ErrorMsg(, ex)
        End Try
    End Sub

    Private Sub frmCalcAggregate_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        Static AlreadyShown As Boolean = False
        If Not AlreadyShown Then frmInfoMsg.ShowInfoMsg("Aggregate Data", "The aggregate data calculation tool has been recently enhanced in a number of ways:\n\n\t\b Spatial aggregation is now possible by selecting the Spatial tab and selecting which Station field is to be used to aggregate multiple stations together. For example, if Branch ID is chosen, data from all stations having a given Branch ID will be compiled, aggregated in time, and assigned a new Station ID equal to the value of the Branch ID. If you choose, you can add new Stations support records that match these calculated records.\n\n\t\b A new Operation type has been added: median value.\n\n\t\b You can now also specify LCode and SCode values to be assigned to the newly computed records.\n\n\t\b You now have the option to create a new table into which computed values will be placed.\n\n\t\b A new Aggregation Period option has been added called 'Four Seasons (Annual Summary)'. This is a special option in which data (possibly spatially aggregated) will be combined using the indicated Operation (e.g., mean, median, etc.) for each of the four seasons. If data for all four are present, these will then be combined using 'Operation to Combine Seasons' to compute an annual value which will then be added to the output table. The 'Sort by Date-Time' report will be the best way to output these new data.")
        AlreadyShown = True
    End Sub

    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        ShowHelp(Me, "19")
    End Sub

    Private Sub cboTableName_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboTableName.SelectionChangeCommitted
        frmCalc.TableSelectionCommitted(cboTableName)
    End Sub

    Private Sub cboAggregation_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboAggregation.SelectedIndexChanged
        If cboAggregation.Text.StartsWith("Four") Then
            lblDate1.Text = "Winter Starting Date:"
            cboMonth1.Text = GetSetting(REGAPP, Name, "WinterMonth", "January")
            cboDay1.Text = GetSetting(REGAPP, Name, "WinterDay", 1)
            lblDate1.Visible = True : cboMonth1.Visible = True : cboDay1.Visible = True
            lblDate2.Visible = False : cboMonth2.Visible = False : cboDay2.Visible = False
            lblOperationSeason.Visible = True : cboOperationSeason.Visible = True
        ElseIf cboAggregation.Text.StartsWith("Growing") Then
            lblDate1.Text = "Growing Season Starting Date:"
            cboMonth1.Text = GetSetting(REGAPP, Name, "GrowingMonth1", "March")
            cboDay1.Text = GetSetting(REGAPP, Name, "GrowingDay1", 15)
            cboMonth2.Visible = True
            cboDay2.Visible = True
            cboMonth2.Text = GetSetting(REGAPP, Name, "GrowingMonth2", "November")
            cboDay2.Text = GetSetting(REGAPP, Name, "GrowingDay2", 15)
            lblDate1.Visible = True : cboMonth1.Visible = True : cboDay1.Visible = True
            lblDate2.Visible = True : cboMonth2.Visible = True : cboDay2.Visible = True
            lblOperationSeason.Visible = False : cboOperationSeason.Visible = False
        Else
            lblDate1.Visible = False : cboMonth1.Visible = False : cboDay1.Visible = False
            lblDate2.Visible = False : cboMonth2.Visible = False : cboDay2.Visible = False
            lblOperationSeason.Visible = False : cboOperationSeason.Visible = False
        End If
    End Sub

    Private Sub cboSummaryField_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboSummaryField.SelectedIndexChanged
        chkAppendStations.Visible = cboSummaryField.SelectedIndex > 0
    End Sub

    Private Sub cboCCodeOut_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboCCodeOut.SelectionChangeCommitted
        frmCalc.CCodeSelectionCommitted(cboCCodeOut)
    End Sub
End Class
